package com.carleasoft.mps.data.mybatisplus.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.carleasoft.mps.core.user.ThreadUserContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.function.Supplier;

/**
 * @author ztm
 * @date 2021-07-08 22:22
 * @project jmrh
 */
@Slf4j
@Component
public class CarleaSoftMetaObjectHandler implements MetaObjectHandler {

    @PostConstruct
    public void printInfo() {
        log.info("Mybatis-plus 属性填充配置类准备加载");
    }

    /**
     * 当执行Insert的时候被拦截
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class);
        this.strictInsertFill(metaObject,"createPersonCode",() ->ThreadUserContext.getCurrentCacheUser().getUserCode(),String.class);
        this.strictInsertFill(metaObject,"createPersonName",() ->ThreadUserContext.getCurrentCacheUser().getUserName(),String.class);
        this.strictInsertFill(metaObject, "isDelete", () -> 0, Integer.class);
        this.strictInsertFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class);
        this.strictInsertFill(metaObject,"updatePersonCode",() ->ThreadUserContext.getCurrentCacheUser().getUserCode(),String.class);
        this.strictInsertFill(metaObject,"updatePersonName",() ->ThreadUserContext.getCurrentCacheUser().getUserName(),String.class);
        // 新增组织和部门
        this.strictInsertFill(metaObject,"deptCode", () -> ThreadUserContext.getCurrentCacheUser().getDeptCode(),String.class);
        this.strictInsertFill(metaObject,"deptName", () -> ThreadUserContext.getCurrentCacheUser().getDeptName(),String.class);
        this.strictInsertFill(metaObject,"organizationCode", () -> ThreadUserContext.getCurrentCacheUser().getOrganizationCode(),String.class);
        this.strictInsertFill(metaObject,"organizationName", () -> ThreadUserContext.getCurrentCacheUser().getOrganizationName(),String.class);
    }

    /**
     * 当执行Update的时候被拦截
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新时间
        this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class);
        this.strictUpdateFill(metaObject,"updatePersonCode",() ->ThreadUserContext.getCurrentCacheUser().getUserCode(),String.class);
        this.strictUpdateFill(metaObject,"updatePersonName",() ->ThreadUserContext.getCurrentCacheUser().getUserName(),String.class);
    }
}
